package com.voice.server.auth.handle;

import com.voice.core.entity.HttpHeader;
import com.voice.server.auth.Authorization;
import com.voice.server.entity.AppToken;
import com.voice.server.repository.AppTokenRepository;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component("appKey")
public class AppKeyAuthorization implements Authorization {

    @Autowired
    private AppTokenRepository appTokenRepository;

    private static final String PARAM_TIMESTAMP = "param-timestamp";
    private static final String PARAM_SIGN = "param-sign";
    private static final String PARAM_SIGN_METHOD = "param-sign-method";
    private static final int expireTime=1000*60*10;

    @Override
    public String authorization(HttpHeader requestHeader) {
        String appKey=requestHeader.get("appKey",String.class);
        String method=requestHeader.get(PARAM_SIGN_METHOD,String.class);
        String validSign=requestHeader.get(PARAM_SIGN,String.class);
        long now=requestHeader.get(PARAM_TIMESTAMP,Long.class);

        if(System.currentTimeMillis()-now>expireTime) return null;
        AppToken appToken=appTokenRepository.findByAppKey(appKey);
        if(appToken==null) return null;
        String appSecret =appToken.getAppSecret();
        String signContent = "appSecret" + appSecret +"timestamp" + now;
        try {
            String sign = (new HmacUtils(HmacAlgorithms.valueOf(method), appSecret)).hmacHex(signContent);
            if(!sign.equals(validSign)) return null;
        }catch (IllegalArgumentException e){
            return null;
        }
        return appToken.getUserId();
    }
}
